package com.zj.fx.service.month;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zj.fx.common.base.BaseService;
import com.zj.fx.common.support.ConvertUtil;
import com.zj.fx.mapper.month.MonthSupplytaskDtlMapper;
import com.zj.fx.mapper.month.MonthSupplytaskMapper;
import com.zj.fx.model.custom.Tablepar;
import com.zj.fx.model.month.*;
import com.zj.fx.shiro.util.ShiroUtils;
import com.zj.fx.util.SnowflakeIdWorker;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 月度供电所填报任务填报明细 MonthSupplytaskService
 *
 * @author SQL_自动生成
 * @Title: MonthSupplytaskService.java 
 * @Package com.zj.fx.service 
 * @email ${email}
 * @date 2023-06-09 17:15:40  
 **/
@Service
public class MonthSupplytaskAuditService implements BaseService<MonthSupplytask, MonthSupplytaskExample> {
    @Autowired
    private MonthSupplytaskMapper monthSupplytaskMapper;

    @Autowired
    private MonthSupplytaskDtlMapper monthSupplytaskDtlMapper;

    @Autowired
    private MonthAuditDtlService monthAuditDtlService;


    /**
     * 分页查询
     *
     * @param
     * @param
     * @return
     */
    public PageInfo<MonthSupplytask> list(Tablepar tablepar, MonthSupplytask MonthSupplytask) {
        MonthSupplytaskExample testExample = new MonthSupplytaskExample();
        //搜索
        if (StrUtil.isNotEmpty(tablepar.getSearchText())) {//小窗体
            testExample.createCriteria().andLikeQuery2(tablepar.getSearchText());
        } else {//大搜索
            testExample.createCriteria().andLikeQuery(MonthSupplytask);
        }
        //表格排序
        //if(StrUtil.isNotEmpty(tablepar.getOrderByColumn())) {
        //	testExample.setOrderByClause(StringUtils.toUnderScoreCase(tablepar.getOrderByColumn()) +" "+tablepar.getIsAsc());
        //}else{
        //	testExample.setOrderByClause("id ASC");
        //}
        PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
        List<MonthSupplytask> list = monthSupplytaskMapper.selectByExample(testExample);
        PageInfo<MonthSupplytask> pageInfo = new PageInfo<MonthSupplytask>(list);
        return pageInfo;
    }

    /**
     * 分页查询
     *
     * @param
     * @param
     * @return
     */
    public PageInfo<MonthSupplytask> list4self(Tablepar tablepar, MonthSupplytask monthSupplytask) {
        //分页查询
        PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
        monthSupplytask.setDeptId(ShiroUtils.getDepId());
        List<MonthSupplytask> list = monthSupplytaskMapper.query4selfAudit(monthSupplytask);

        //查询对应供电所任务的审核明细（审核状态及审核完成时间）
        for (MonthSupplytask supplytask : list) {
            MonthAuditDtl monthAuditDtl = new MonthAuditDtl();
            monthAuditDtl.setFkTaskId(supplytask.getId());
            List<MonthAuditDtl> monthAuditDtls = monthAuditDtlService.findbyTaskIDandDepID(monthAuditDtl);
            if (monthAuditDtls!=null && monthAuditDtls.size()>0){
                MonthAuditDtl monthAuditDtl1 = monthAuditDtls.get(0);
                supplytask.setAuditState(monthAuditDtl1.getTaskState());
                supplytask.setAuditDtlDate(monthAuditDtl1.getAuditDate());
            }
        }
        PageInfo<MonthSupplytask> pageInfo = new PageInfo<MonthSupplytask>(list);
        return pageInfo;
    }

    @Override
    public int deleteByPrimaryKey(String ids) {

        List<String> lista = ConvertUtil.toListStrArray(ids);
        MonthSupplytaskExample example = new MonthSupplytaskExample();
        example.createCriteria().andIdIn(lista);
        return monthSupplytaskMapper.deleteByExample(example);


    }


    @Override
    public MonthSupplytask selectByPrimaryKey(String id) {

        return monthSupplytaskMapper.selectByPrimaryKey(id);

    }


    @Override
    public int updateByPrimaryKeySelective(MonthSupplytask record) {
        return monthSupplytaskMapper.updateByPrimaryKeySelective(record);
    }


    /**
     * 添加
     */
    @Override
    public int insertSelective(MonthSupplytask record) {

        //添加雪花主键id
        record.setId(SnowflakeIdWorker.getUUID());


        return monthSupplytaskMapper.insertSelective(record);
    }


    @Override
    public int updateByExampleSelective(MonthSupplytask record, MonthSupplytaskExample example) {

        return monthSupplytaskMapper.updateByExampleSelective(record, example);
    }


    @Override
    public int updateByExample(MonthSupplytask record, MonthSupplytaskExample example) {

        return monthSupplytaskMapper.updateByExample(record, example);
    }

    @Override
    public List<MonthSupplytask> selectByExample(MonthSupplytaskExample example) {

        return monthSupplytaskMapper.selectByExample(example);
    }


    @Override
    public long countByExample(MonthSupplytaskExample example) {

        return monthSupplytaskMapper.countByExample(example);
    }


    @Override
    public int deleteByExample(MonthSupplytaskExample example) {

        return monthSupplytaskMapper.deleteByExample(example);
    }

    public MonthSupplytaskDtl updateAudit(MonthSupplytaskDtl monthSupplytaskDtl) {
        //----------------0、原始数据获取
        String id = monthSupplytaskDtl.getId();
        String reviewValue = monthSupplytaskDtl.getReviewValue();//几处
        //----------------1、查询当前5级项目信息
        monthSupplytaskDtl = monthSupplytaskDtlMapper.selectByPrimaryKey(id);
        String parentId = monthSupplytaskDtl.getFkParentProjectId();
        String countAmount = monthSupplytaskDtl.getCountAmount();//加分扣分
        String countRegulation = monthSupplytaskDtl.getCountRegulation();//系数

        //-------------------2、查询当前5级项目对应四级项目信息，获取关键数值
        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
        criteria.andNumEqualTo(parentId);
        criteria.andFkTaskIdEqualTo(monthSupplytaskDtl.getFkTaskId());
        List<MonthSupplytaskDtl> monthSupplytaskDtls = monthSupplytaskDtlMapper.selectByExample(monthSupplytaskDtlExample);
        MonthSupplytaskDtl monthSupplytaskDtl4 = monthSupplytaskDtls.get(0);
        String fullMark = monthSupplytaskDtl4.getFullMark();//满分
        String maxdeduction = monthSupplytaskDtl4.getFullMark();//最多扣分------坑----最多扣分和满分是否相同，不相同要加字段

        //如果填报值为空并传到后端，说明之前完成了填写并完成了计算，此时应该找到该条记录，将填写值和审核扣分值置为null，对应四级审核得分置为null，是否审核修改改为"否"
        if (Strings.isNotBlank(reviewValue)) {
            //------------------3、计算当前5级项目的扣分。更新当前五级项目
            //评分策略（1输入量值（目标）/2是否/3输入量值）
            BigDecimal totalSub = BigDecimal.ZERO;
            if (monthSupplytaskDtl.getTactics().equals(MonthConstant.DTL_TACTIC_TARGET)) {
                if (monthSupplytaskDtl.getSelfValue().equals(reviewValue)){
                    reviewValue = "";
                    monthSupplytaskDtl.setIsAuditedit(MonthConstant.NOT);
                    monthSupplytaskDtl.setReviewScore("");
                }else {
                    //目标值
                    BigDecimal targetScore = new BigDecimal(monthSupplytaskDtl.getTargetScore());
                    BigDecimal reviewValuebigDec = new BigDecimal(reviewValue);
                    BigDecimal countAmountDec = new BigDecimal(countAmount);
                    BigDecimal countRegulationDec = new BigDecimal(countRegulation);
                    //判断加减分，如果是加分，逻辑为大于目标值则按规则扣分
                    if (countAmountDec.compareTo(BigDecimal.ZERO) > 0) {
                        if (reviewValuebigDec.compareTo(targetScore) > 0) {
                            BigDecimal cha = reviewValuebigDec.subtract(targetScore);
                            BigDecimal count = cha.divide(countAmountDec, 0, RoundingMode.DOWN);
                            totalSub = count.multiply(countRegulationDec);
                        }
                    } else {
                        if (reviewValuebigDec.compareTo(targetScore) < 0) {
                            BigDecimal cha = targetScore.subtract(reviewValuebigDec);
                            BigDecimal count = cha.divide(countAmountDec.abs(), 0, RoundingMode.DOWN);
                            totalSub = count.multiply(countRegulationDec);
                        }
                    }
                    monthSupplytaskDtl.setReviewScore(totalSub.toString());
                    monthSupplytaskDtl.setIsAuditedit(MonthConstant.IS);
                }
            } else if (monthSupplytaskDtl.getTactics().equals(MonthConstant.DTL_TACTIC_ISORNOT)) {

                //20230629 增加一种情形，是否选项类型，当选择了与自评价值不同选项，又改回相同选项，此时应该清空审核值与审核得分
                if (monthSupplytaskDtl. getSelfValue().equals(reviewValue)){
                    reviewValue = "";
                    monthSupplytaskDtl.setIsAuditedit(MonthConstant.NOT);
                    monthSupplytaskDtl.setReviewScore("");
                } else {
                    //如果扣分项与当前项一致，开始计算扣分分数
                    if (monthSupplytaskDtl.getTypeOption().toString().equals(reviewValue)) {
                        //扣分
                        BigDecimal multiply = new BigDecimal(countAmount).multiply(new BigDecimal(countRegulation)).abs();
                        //实际扣分--对比最大扣分上限值
                        if (multiply.compareTo(new BigDecimal(maxdeduction)) > 0) {
                            totalSub = new BigDecimal(maxdeduction);
                        } else {
                            totalSub = multiply;
                        }
                    }
                    monthSupplytaskDtl.setReviewScore(totalSub.toString());
                    monthSupplytaskDtl.setIsAuditedit(MonthConstant.IS);
                }
            } else if (monthSupplytaskDtl.getTactics().equals(MonthConstant.DTL_TACTIC_VALUE)) {
                if (monthSupplytaskDtl. getSelfValue().equals(reviewValue)){
                    reviewValue = "";
                    monthSupplytaskDtl.setIsAuditedit(MonthConstant.NOT);
                    monthSupplytaskDtl.setReviewScore("");
                }else {
                    //当前都按照扣分来计算 取绝对值
                    //扣分
                    BigDecimal multiply = new BigDecimal(countAmount).multiply(new BigDecimal(countRegulation)).multiply(new BigDecimal(reviewValue)).abs();
                    //实际扣分--对比最大扣分上限值
                    if (multiply.compareTo(new BigDecimal(maxdeduction)) > 0) {
                        totalSub = new BigDecimal(maxdeduction);
                    } else {
                        totalSub = multiply;
                    }
                    monthSupplytaskDtl.setReviewScore(totalSub.toString());
                    monthSupplytaskDtl.setIsAuditedit(MonthConstant.IS);
                }
            }
        } else {
            reviewValue = "";
            monthSupplytaskDtl.setIsAuditedit(MonthConstant.NOT);
            monthSupplytaskDtl.setReviewScore("");
        }

        //更新5级项目审核得分，用于前端表格展示
        monthSupplytaskDtl.setReviewValue(reviewValue);
        monthSupplytaskDtlMapper.updateByPrimaryKeySelective(monthSupplytaskDtl);

        BigDecimal pro4Score = new BigDecimal(fullMark);
        //四级项目下有多条五级项目的。每次循环计算分数
        MonthSupplytaskDtl monthSupplytaskDtl1 = new MonthSupplytaskDtl();
        monthSupplytaskDtl1.setFkTaskId(monthSupplytaskDtl.getFkTaskId());
        monthSupplytaskDtl1.setFkParentProjectId(monthSupplytaskDtl.getFkParentProjectId());
        //查询出四级项目下对应的所有五级项目
        BigDecimal grade5TotalScore = BigDecimal.ZERO;
        List<MonthSupplytaskDtl> monthSupplytaskDtls1 = this.findgrade5by4(monthSupplytaskDtl1);
        //查询出五级项目中是否审核更正状态为"是"和"否"的两个List
        //状态为是的，计算审核总分
        //状态为否的，计算自评总得分
        //两者相加为总扣分，再与最大扣分值做比较
        List<MonthSupplytaskDtl> iscollect = monthSupplytaskDtls1.stream().filter(s -> MonthConstant.IS.equals(s.getIsAuditedit())).collect(Collectors.toList());
        List<MonthSupplytaskDtl> notcollect = monthSupplytaskDtls1.stream().filter(s -> MonthConstant.NOT.equals(s.getIsAuditedit())).collect(Collectors.toList());
        BigDecimal isAuditScore = iscollect.stream().map(MonthSupplytaskDtl::getReviewScore).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal notAuditScore = notcollect.stream().map(MonthSupplytaskDtl::getSelfScore).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (notcollect.size() != monthSupplytaskDtls1.size()) {
            grade5TotalScore = isAuditScore.add(notAuditScore);
            if (grade5TotalScore.compareTo(new BigDecimal(maxdeduction)) > 0) {
                pro4Score = pro4Score.subtract(new BigDecimal(maxdeduction)).setScale(2);//四舍五入保留两位小数
            } else {
                pro4Score = pro4Score.subtract(grade5TotalScore).setScale(2);
            }
        } else {
            pro4Score = null;
        }


        //更新4级项目自评价得分，用于后端统计计算
        if (pro4Score == null) {
            monthSupplytaskDtl4.setReviewScore("");
            monthSupplytaskDtl4.setIsAuditedit(MonthConstant.NOT);
        } else {
            monthSupplytaskDtl4.setReviewScore(pro4Score.toString());
            monthSupplytaskDtl4.setIsAuditedit(MonthConstant.IS);
        }

        return monthSupplytaskDtl4;
    }

    /**
     * 查询出四级项目下对应的所有五级项目
     *
     * @param monthSupplytaskDtl1
     * @return
     */
    public List<MonthSupplytaskDtl> findgrade5by4(MonthSupplytaskDtl monthSupplytaskDtl1) {
        return monthSupplytaskDtlMapper.findgrade5by4(monthSupplytaskDtl1);
    }

}
